﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace CSharp.Infrastructure
{
    public class CookieHelper
    {
        private const int INTERNET_COOKIE_HTTPONLY = 0x00002000;
        private const int INTERNET_COOKIE = 0x2000;
        [DllImport("wininet.dll", SetLastError = true)]
        private static extern bool InternetGetCookieEx(
        string url,
            string cookieName,
            StringBuilder cookieData,
        ref int size,
            int flags,
            IntPtr pReserved);

        /// <summary>
        /// Returns cookie contents as a string
        /// </summary>
        /// <param name="url">http://***.***.****</param>
        /// <returns></returns>
        public static string GetCookie(string url)
        {
            int size = 4096;
            StringBuilder sb = new StringBuilder(size);
            if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE, IntPtr.Zero))
            {
                if (size < 0)
                {
                    return null;
                }

                sb = new StringBuilder(size);
                if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero))
                {
                    return null;
                }
            }

            Logs.WriteLog(LogType.Info, "cookie new size " + size);

            return sb.ToString();
        }

        /// <summary>
        /// Returns cookie contents as a string
        /// </summary>
        /// <param name="url">http://***.***.****</param>
        /// <returns></returns>
        public static string GetCookie2(string url)
        {
            int size = 4096;
            StringBuilder sb = new StringBuilder(size);
            if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero))
            {
                if (size < 0)
                {
                    return null;
                }

                sb = new StringBuilder(size);
                if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE, IntPtr.Zero))
                {
                    return null;
                }
            }

            Logs.WriteLog(LogType.Info, "cookie new size " + size);

            return sb.ToString();
        }
    }
}
